﻿/// <reference path="../Core.ts" />

module Supernova {

    export class Artillery {

        public owner: OwnerType = OwnerType.none;
        public sourceBody: Body = null;
        public sourceShip: Ship = null;
        public targetBody: Body = null;
        public x: number = 0;
        public y: number = 0;
        public speed: number = 0;
        public strength: number = 1;
        public ignoreOrbitals: boolean = false;

        constructor(sourceBody: Body, sourceShip: Ship, targetBody: Body) {
            this.sourceBody = sourceBody;
            this.sourceShip = sourceShip;
            this.targetBody = targetBody;
            if (sourceBody !== null) {
                this.x = sourceBody.x;
                this.y = sourceBody.y;
                this.owner = sourceBody.system.owner;
            }
            if (sourceShip !== null) {
                this.x = sourceShip.currentLocation.x;
                this.y = sourceShip.currentLocation.y;
                this.owner = sourceShip.owner;
            }            
            this.speed = ARTILLERY_SPEED_INITIAL;
        }

        bombardAction() {

            // Decide whether to remove orbital or population point
            var playOrbital = false;
            var playBody = false;
            for (var i = 0; i < this.strength; i++) {
                if (this.targetBody.facilities.orbitals > 0 && this.ignoreOrbitals === false) {
                    this.targetBody.facilities.orbitals--;
                    playOrbital = this.owner == OwnerType.human || this.targetBody.system.owner == OwnerType.human;
                } else {
                    this.targetBody.population--;
                    playBody = this.owner == OwnerType.human || this.targetBody.system.owner == OwnerType.human;
                }

                // Has the body been cleared?
                if (this.targetBody.population < 1) this.targetBody.depopulate();
            }

            // Play sound
            if (playBody) { Sounds.play(Sounds.items.bombardPlanet); } else { Sounds.play(Sounds.items.bombardOrbital); }

            // Add messages
            var systemPopulation = this.targetBody.system.calculatePopulation();
            if (this.targetBody.system.owner == OwnerType.human || galaxy.mode == GameMode.replay) {
                if (systemPopulation <= 0) {
                    Notices.addMessage(MessageType.fatal, 'System ' + this.targetBody.system.name + ' has been completely depopulated!');
                } else {
                    Notices.addMessage(MessageType.fatal, 'System ' + this.targetBody.system.name + ' is being bombarded!');
                }
            }

            // Make neutral system if completely depopulated
            if (systemPopulation <= 0) this.targetBody.system.depopulate();
        }

    }

}